package com.atguigu.config;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.*;

@Component   //被扫描 需要指定扫描路径
public class MyUserDetailService implements UserDetailsService {

    @Reference
    private AdminService adminService;
    @Reference
    private PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据username获取Admin信息
        Admin admin = this.adminService.getByUsername(username);
        //如果 admin为空  username都不对 直接返回异常
        if (admin == null) {
            throw new UsernameNotFoundException("userName为空");
        }
        //如果 admin不为空 说明 username正确，需要比较密码  不需要开发者来比较 只要传递数据即可
        //由springSecurity来完成密码的比较
        Collection<GrantedAuthority> authorities=new ArrayList<>();
        List<String> codeList = this.permissionService.findCodeListByAdminId(admin.getId());
        for(String code :codeList){
            authorities.add(new SimpleGrantedAuthority(code));
        }

        User user = new User(username, admin.getPassword(), authorities);

     return  user;
    }
}
